package com.xiangban.utils;


import com.xiangban.model.dto.MetaDto;
import com.xiangban.model.dto.PermissionMenuDto;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TreeUtil {

    /**
     * 创建树结构
     * @param regionTrees
     * @return
     */
    public static List<PermissionMenuDto> tree(List<PermissionMenuDto> regionTrees) {
        //返回的节点树

        List<PermissionMenuDto> rootNodes = new ArrayList<>();
        Iterator<PermissionMenuDto> it = regionTrees.iterator();
        while (it.hasNext()) {
            PermissionMenuDto next = it.next();
            MetaDto metaDto = new MetaDto();
            metaDto.setTitle(next.getTitle());
            metaDto.setIcon(next.getIcon());
            metaDto.setAffix(next.isAffix());

            next.setMeta(metaDto);
            //parent（上级Id）为0的是根节点
            if ("0".equals(next.getPId().toString())) {
                rootNodes.add(next);
                it.remove();
            }
        }
        //遍历，找到二级节点
        for (PermissionMenuDto regionTree : rootNodes) {
            List<PermissionMenuDto> child = getChild(regionTrees, regionTree.getId().toString());
            regionTree.setChildren(child);
        }
        return rootNodes;

    }

    /**
     * 查子节点
     *
     * @param regions
     * @param parentId
     * @return
     */
    private static List<PermissionMenuDto> getChild(List<PermissionMenuDto> regions, String parentId) {

        //子节点列表
        List<PermissionMenuDto> childList = new ArrayList<>();
        Iterator<PermissionMenuDto> it = regions.iterator();
        while (it.hasNext()) {
            PermissionMenuDto regionTree = it.next();
            if (parentId.equals(regionTree.getPId().toString())) {
                childList.add(regionTree);
                it.remove();
            }
        }

        //遍历 递归获取子节点的子节点
        for (PermissionMenuDto regionTree : childList) {
            List<PermissionMenuDto> child = getChild(regions, regionTree.getId().toString());
            regionTree.setChildren(child);
        }
        //递归出口  childList长度为0
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }
}
